package com.easy.activiti;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Optional;

/**
 * @author zhouchuang
 * @date 2024-11-14 14:30:50
 */
public class RestoreJsessionIdCookieFilter implements Filter {
    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        if(!isExcludedUrls(servletRequest)){
            Optional<Cookie> bsJsessionidOptional = Arrays.stream(Optional.ofNullable(httpServletRequest.getCookies()).orElse(new Cookie[]{})).filter(t->t.getName().equals("BS_JSESSIONID")).findFirst();
            if(bsJsessionidOptional.isPresent()){
                logger.error("===========BSJSESSIONID 存在============");
                //如果存在BS_JSESSIONID，则替换JSESSIONID
                String bsJsessionId = bsJsessionidOptional.get().getValue();
                Optional<Cookie> jsessionidOptional  =  Arrays.stream(httpServletRequest.getCookies()).filter(t->t.getName().equals("JSESSIONID")).findFirst();
                if(jsessionidOptional.isPresent()){
                    if( !jsessionidOptional.get().getValue().equals(bsJsessionId)){
                        logger.error("===========JSESSIONID 存在============");
                        for (int i = 0; i < httpServletRequest.getCookies().length; i++) {
                            Cookie cookie = httpServletRequest.getCookies()[i];
                            if(cookie.getName().equals("JSESSIONID")){
                                Cookie newCookie  =  new Cookie("JSESSIONID",bsJsessionId);
                                newCookie.setPath("/"); // 设置路径为根路径
                                newCookie.setHttpOnly(true); // 设置HttpOnly属性
                                httpServletRequest.getCookies()[i] = newCookie;

                                //添加新的JSESSIONID
                                httpServletResponse.addCookie(newCookie);
                                break;
                            }
                        }
                    }

                    //删除BS
                    Cookie bsCookie = new Cookie("BS_JSESSIONID", bsJsessionId);
                    bsCookie.setMaxAge(0); //删除
                    bsCookie.setPath("/"); // 设置路径为根路径
                    bsCookie.setHttpOnly(true); // 设置HttpOnly属性
                    httpServletResponse.addCookie(bsCookie);
                }
            }
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }

    private boolean isExcludedUrls(ServletRequest servletRequest){
        String path = ((HttpServletRequest) servletRequest).getRequestURI();
        return path.contains(".js")
                || path.contains(".css")
                || path.contains(".woff");
    }


}
